<?php

/**
 * 每天获取最新新闻数据
 */

namespace app\plan\controller;

use GuzzleHttp\Client;
use think\Cache;

class News
{
    public function getNews()
    {
        try {
            $listKey = 'news:hash:newlist';

            $client = new Client();
            // 发送GET请求并获取API数据
            $url = "http://apis.juhe.cn/fapigx/caijing/query";
            $params = [
                "key" => "e81403fa59ae93176a80b74880169d13",
                "type" => "top",
            ];

            $response = $client->get($url, ['query' => $params]);
            $result = json_decode($response->getBody(), true);

            $newslist = $result['result']['newslist'];
            // print_r($newslist);die;

            // 获取redis连接
            $redis = Cache::store('redis')->handler();

            // 获取今天的日期
            $today = date('Y-m-d');

            $allNews = [];
            // 存储今天的数据到Redis，设置12小时过期
            foreach ($newslist as $k => $v) {
                // 只存储今天和昨天和前天的数据
                if (date('Y-m-d', strtotime($v['ctime'])) === $today || date('Y-m-d', strtotime($v['ctime']) + 86400) === $today || date('Y-m-d', strtotime($v['ctime']) + 172800) === $today) {

                    // 去除描述中的时间信息
                    $description = preg_replace('/\d{4}-\d{2}-\d{2}\s*\d{2}:\d{2}/', '', $v['description']);

                    // 存储所有字段到Redis中
                    $data = [
                        $v['ctime'],
                        $v['title'],
                        $description,
                        $v['source'],
                        $v['picUrl'],
                        $v['url'],
                    ];

                    // 转换编码
                    $data = array_map(function ($item) {
                        return mb_convert_encoding($item, 'UTF-8', 'auto');
                    }, $data);

                    // 获取成功返回数据
                    $stockInfo = [
                        'ctime' => $data[0],
                        'title' => $data[1],
                        'description' => $description,
                        'source' => $data[3],
                        'picUrl' => $data[4],
                        'url' => $data[5],
                    ];


                    if ($description != '') {
                        // 数据整合返回
                        $allNews[] = $stockInfo;

                        // 存入redis
                        $redis->hset($listKey, $k + 1, implode('|', $data));
                        // 设置过期时间为12小时
                        $redis->expire($listKey, 12 * 60 * 60);
                    }
                }
            }
            return $allNews;
        } catch (\Exception $e) {
            // 处理请求失败的情况
            echo 'Error: ' . $e->getMessage();
        }
    }
}
